/**
 * kaGridListHeaderMenu 封装 列表头菜单按钮
 * 
 * 版本：v1.0
 * 
 * Stanley
 **/
layui.define(['jquery'],
    function (exports) {
        var $ = layui.jquery;
        var kaGridListHeaderMenu = new function () {
            this.init = function (thatThis) {
                var layTableIdClassName = "*[lay-table-id='" + thatThis.id + "']";
                var layuiTableHeaderClassName = ".layui-table-header";
                var layuiTableCellClassName = ".layui-table-cell";
                var kaGridAllParamsName = "table_Params_" + thatThis.id;
                $(layTableIdClassName).find(layuiTableHeaderClassName).each(function () {
                    $(this).find(layuiTableCellClassName).each(function () {
                        var className = $(this).attr("class");
                        if (className.indexOf("laytable-cell-checkbox") == -1 && className.indexOf("laytable-cell-numbers") == -1) {
                            var thisParent = $(this).parent();
                            var dataFieldId = thisParent.attr('data-field');
                            var pader = top.kaGridAllParams[kaGridAllParamsName];// 获取表格字段
                            var dataFieldIdStr = dataFieldId + `_` + thatThis.id + "_div";
                            if ($("#" + dataFieldIdStr + "_i").length) {
                                $("#" + dataFieldIdStr + "_i").attr("style", layui.kaGridListHeaderMenu.getHtml({ type: 11, thisParent: thisParent, dataFieldIdStr: dataFieldIdStr, tableId: thatThis.id, dataFieldId: dataFieldId, pader: pader }));
                            } else {
                                $(this).append(layui.kaGridListHeaderMenu.getHtml({ type: 1, thisParent: thisParent, dataFieldIdStr: dataFieldIdStr, tableId: thatThis.id, dataFieldId: dataFieldId, pader: pader }));
                                var dropdownHtml = layui.kaGridListHeaderMenu.getHtml({ type: 2, thisParent: thisParent, dataFieldIdStr: dataFieldIdStr, tableId: thatThis.id, dataFieldId: dataFieldId, pader: pader });
                                var dropdown = layui.dropdown;
                                // 自定义内容
                                dropdown.render({
                                    id: dataFieldIdStr,
                                    elem: '#' + dataFieldIdStr,
                                    content: dropdownHtml,
                                    tableid: thatThis.id,
                                    dataFieldId: dataFieldId,
                                    style: 'width: 250px; height: 300px; box-shadow: 1px 1px 30px rgb(0 0 0 / 12%);',
                                    shade: [0.6, '#FFF'], // 弹出时开启遮罩 --- 2.8+
                                    ready: function () {
                                        layui.form.render();
                                        var tableid = this.tableid;
                                        var dataFieldId = this.dataFieldId;
                                        var params = top.kaGridAllParams["table_Params_" + tableid];// 获取表格字段
                                        // input 绑定事件
                                        layui.kaGridListHeaderMenu.toolIput(tableid, dataFieldId, params.filterOne);
                                        // button 绑定事件
                                        layui.kaGridListHeaderMenu.toolButton(tableid, dataFieldId);
                                        // 初始化数据
                                        var layuiTreeData = layui.kaGridListHeaderMenu.toolFilter(tableid, dataFieldId, undefined, params.filterOne == undefined ? true : (params.filterOne == dataFieldId ? true : undefined));
                                        layui.tree.render({
                                            id: 'tree_' + tableid + "_" + dataFieldId,
                                            elem: '#tree_' + tableid + "_" + dataFieldId,
                                            data: layuiTreeData,
                                            showCheckbox: true,
                                            onlyIconControl: true
                                        });
                                    }
                                });
                            }
                        }
                    })
                });
            }
            this.toolIput = function (tableid, dataFieldId, filterOne) { // 搜索Input
                $("#" + tableid + `_input_` + dataFieldId).keyup(function (event) {
                    var kaGridAllParamsName = "table_Params_" + tableid;
                    var tableid = $(this).attr("tableid"); // 表格ID
                    var dataFieldId = $(this).attr("dataFieldId"); // 字段ID
                    var value = $(this).val(); // 值
                    var params = top.kaGridAllParams[kaGridAllParamsName];// 获取表格字段
                    var layuiTreeData = layui.kaGridListHeaderMenu.toolFilter(tableid, dataFieldId, value, filterOne == undefined ? true : (filterOne == dataFieldId ? true : undefined)); // 新的Html
                    layui.tree.render({
                        id: 'tree_' + tableid + "_" + dataFieldId,
                        elem: '#tree_' + tableid + "_" + dataFieldId,
                        data: layuiTreeData,
                        showCheckbox: true,
                        onlyIconControl: true
                    });
                    layui.form.render();
                });
            }
            this.toolButton = function (tableid, dataFieldId) { // 确定选择
                $("#" + tableid + `_button_` + dataFieldId).click(function () {
                    var tableid = $(this).attr("tableid"); // 表格ID
                    var dataFieldId = $(this).attr("dataFieldId"); // 字段ID
                    var params = top.kaGridAllParams["table_Params_" + tableid];// 获取表格字段
                    var formValuesAll = layui.tree.getChecked('tree_' + tableid + "_" + dataFieldId);
                    var kaGridData = layui.kaGridData.get({ id: tableid, dataBoolean: 0 }, true);//获取值
                    if (formValuesAll.length > 0) { // 分裂
                        var formValues = formValuesAll[0].children;
                        var valuenumber = formValuesAll[0].valuenumber;
                        // 加载渲染结果
                        for (var i in kaGridData) {
                            var item = kaGridData[i][dataFieldId];
                            var kaGridChooseFilter = kaGridData[i]["kaGridChooseFilter"];
                            for (var j in formValues) {
                                var formValue = formValues[j];
                                var value = formValue.value;
                                if (item == value) {
                                    if (kaGridChooseFilter == undefined || kaGridChooseFilter == null) {
                                        kaGridChooseFilter = {};
                                    }
                                    kaGridChooseFilter[dataFieldId] = true;
                                    kaGridData[i]["kaGridChooseFilter"] = kaGridChooseFilter;
                                    break;
                                } else {
                                    if (kaGridChooseFilter != undefined && kaGridChooseFilter != null) {
                                        if (kaGridChooseFilter[dataFieldId] != undefined && kaGridChooseFilter[dataFieldId] != null) {
                                            kaGridData[i].kaGridChooseFilter[dataFieldId] = false;
                                            kaGridData[i]["kaGridChooseFilter"] = kaGridChooseFilter;
                                        } else {
                                            kaGridData[i].kaGridChooseFilter[dataFieldId] = false;
                                            kaGridData[i]["kaGridChooseFilter"] = kaGridChooseFilter;
                                        }
                                    } else {
                                        if (kaGridChooseFilter == undefined || kaGridChooseFilter == null) {
                                            kaGridChooseFilter = {};
                                        }
                                        kaGridChooseFilter[dataFieldId] = false;
                                        kaGridData[i]["kaGridChooseFilter"] = kaGridChooseFilter;
                                    }
                                }
                            }
                        }
                    } else { // 全部取消
                        for (var i in kaGridData) {
                            var kaGridChooseFilter = kaGridData[i]["kaGridChooseFilter"];
                            if (kaGridChooseFilter == undefined || kaGridChooseFilter == null) {
                                kaGridChooseFilter = {};
                            }
                            kaGridChooseFilter[dataFieldId] = false;
                            kaGridData[i]["kaGridChooseFilter"] = kaGridChooseFilter;
                        }
                    }
                    params["dataBoolean"] = 0;
                    if (params.filterOne != undefined && params.filterOne == dataFieldId) {
                        // 判断是否是全选 
                        if (formValues != undefined && valuenumber == formValues.length) {
                            var filtersTwo = params.filtersTwo;
                            if (filtersTwo.get(params.filterOne) != undefined && filtersTwo.get(params.filterOne) != null) {
                                filtersTwo.delete(params.filterOne);
                            }
                            params.filterOne = undefined;
                            if (filtersTwo == undefined || filtersTwo.size == 0) {
                                if (params.url != undefined && params.url != null && params.url != "") {
                                    params["dataBoolean"] = 1;
                                }
                            } else {
                                for (let [key, value] of filtersTwo.entries()) {
                                    params.filterOne = value;
                                    break; // 找到第一个值后退出循环
                                }
                            }
                        }
                    } else {
                        if (params.filterOne == undefined) {
                            if (formValues != undefined && valuenumber == formValues.length) {
                                params.filterOne = undefined;
                                var filtersTwo = params.filtersTwo;
                                if (filtersTwo == undefined || filtersTwo.size == 0) {
                                    if (params.url != undefined && params.url != null && params.url != "") {
                                        params["dataBoolean"] = 1;
                                    }
                                } else {
                                    for (let [key, value] of filtersTwo.entries()) {
                                        params.filterOne = value;
                                        break; // 找到第一个值后退出循环
                                    }
                                }
                            } else {
                                params.filterOne = dataFieldId;
                            }
                        }
                    }
                    var field = layui.form.val(params.id + "_filter");
                    layui.table.reloadData(params.id, {
                        where: field // 搜索的字段
                    }, true);
                    layui.dropdown.close($(this).attr("dropdownId"));
                });
            }
            // 加载筛选值
            this.toolFilter = function (tableid, dataFieldId, value, dataFieldBoolean) {
                var params = { id: tableid, dataBoolean: 0 };
                var kaGridData = layui.kaGridData.get(params, dataFieldBoolean);
                var countMap = new Map();
                var checkedMap = new Map();
                var numberId = 0;
                for (var i in kaGridData) {
                    var itemData = kaGridData[i];
                    var item = itemData[dataFieldId];
                    countMap.set(item, (countMap.get(item) || 0) + 1)
                    // tableData
                    var filter = itemData["kaGridChooseFilter"];
                    if (filter != undefined && filter != null) {
                        var vBoolean = filter[dataFieldId];
                        if (vBoolean) {
                            checkedMap.set(item, itemData);
                            numberId++;
                        }
                    }
                }
                var valuenumberx = 0;
                var numberAll = kaGridData.length;
                var newData = [];
                for (let [key, number] of countMap) {
                    if (value != undefined && value != null && value != "" && key.indexOf(value) == -1) {
                        console.log(key + "_不相同_" + value);
                    } else {
                        var checkedBoolean = false;
                        if (numberId == 0) {
                            checkedBoolean = true;
                        } else {
                            if (checkedMap.get(key) != undefined) {
                                checkedBoolean = true;
                            }
                        }
                        var bfb1 = (parseFloat(number) / parseFloat(numberAll) * 100);
                        var bfb0 = 0;
                        if (bfb1 == 100) {
                            bfb0 = 100;
                        } else {
                            bfb0 = bfb1.toFixed(1)
                        }
                        newData.push({ title: layui.kaGridListHeaderMenu.getHtml({ type: 3, key3: key, number3: number, bfb03: bfb0 }), id: key, value: key, checked: checkedBoolean });
                        valuenumberx++;
                    }
                }
                return [{ title: layui.kaGridListHeaderMenu.getHtml({ type: 4 }), id: dataFieldId + "ALL", spread: true, children: newData, value: dataFieldId, valuenumber: valuenumberx }];
            }
            this.getHtml = function (params) {
                var type = params.type;
                if (type == 1) {
                    var thisParent = params.thisParent;
                    var dataFieldIdStr = params.dataFieldIdStr;
                    var tableId = params.tableId;
                    var dataFieldId = params.dataFieldId;
                    var pader = params.pader;
                    var filtersTwo = pader.filtersTwo;
                    var colorStr = "var(--global-primary-color);";
                    if (filtersTwo != undefined && filtersTwo.get(dataFieldId) != undefined) {
                        colorStr = "#ff9c9c;display:block!important;";
                    }
                    return `<div id="` + dataFieldIdStr + `" dropdownType="0" class="layuiTableHeadTool ` + tableId + `_dropdown` + `"><i id="` + dataFieldIdStr + `_i" style="color:` + (pader.filterOne == undefined ? colorStr : (pader.filterOne == dataFieldId ? "red;display:block!important;" : colorStr)) + `;cursor: pointer;" class="icon Kaultraiconfont Kaultraicon-kehuduan"></i></div>`;
                } else if (type == 11) {
                    var thisParent = params.thisParent;
                    var dataFieldIdStr = params.dataFieldIdStr;
                    var tableId = params.tableId;
                    var dataFieldId = params.dataFieldId;
                    var pader = params.pader;
                    var filtersTwo = pader.filtersTwo;
                    var colorStr = "var(--global-primary-color);";
                    if (filtersTwo != undefined && filtersTwo.get(dataFieldId) != undefined) {
                        colorStr = "#ff9c9c;display:block!important;";
                    }
                    return "color:" + (pader.filterOne == undefined ? colorStr : (pader.filterOne == dataFieldId ? "red;display:block!important;" : colorStr));
                } else if (type == 2) {
                    var thisParent = params.thisParent;
                    var dataFieldIdStr = params.dataFieldIdStr;
                    var tableId = params.tableId;
                    var dataFieldId = params.dataFieldId;
                    var pader = params.pader;
                    var title = thisParent.attr('title');
                    var dropdownHtml = `
                            <div class="dropdownHClass1">` + title + `</div>
                            <input id="` + tableId + `_input_` + dataFieldId + `" type="text" name="` + tableId + `_input_` + dataFieldId + `"  dropdownId="` + dataFieldIdStr + `" tableid="` + tableId + `" dataFieldId="` + dataFieldId + `" placeholder="搜索" class="layui-input dropdownHInput"/>
                            <div id="` + tableId + `_form_` + dataFieldId + `" class="dropdownHForm">
                                <div id="tree_` + tableId + `_` + dataFieldId + `" class="KaGridDropdown"></div>
                            </div>
                            <div style="text-align: right;">
                                <button dropdownId="` + dataFieldIdStr + `"  id="` + tableId + `_button_` + dataFieldId + `" tableid="` + tableId + `" dataFieldId="` + dataFieldId + `" type="button" class="layui-btn layui-btn-xs">确认</button>
                            </div>
                        `
                    return dropdownHtml;
                } else if (type == 3) {
                    var key = params.key3;
                    var number = params.number3;
                    var bfb0 = params.bfb03;
                    return `<div style="margin-left: 5px;width: calc(100% - 81px);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;float: left;">` + key + `</div>` + `<div style="color: #b9b9b9;margin-left: 5px;float: left;">(` + number + `<span class="spanbfb">,<span style="margin-left: 5px;">` + bfb0 + `%</span></span>)</div>`;
                } else if (type == 4) {
                    return `<span style="margin-left: 5px;">全选</span>`;
                }
            }
            this.LAYTABLECOLSFilterForm = function (tableFormId, orderId) {
                var newValue = layui.form.val(tableFormId);
                var oldValue = {};
                layui.$('ul[lay-filter="LAYTABLE_COLS_filter_form"]').find("input").each(function (params) {
                    var key = $(this).attr("name");
                    oldValue[key] = "1";
                });
                var formDatas = [];
                var kanumber = 1;
                for (var key in oldValue) {
                    var formData = {};
                    var value = newValue[key];
                    formData["gridId"] = orderId;
                    formData["kasort"] = kanumber;
                    formData["field"] = key;
                    if (!(value != undefined && value != null && value != "")) {
                        formData["gridId"] = orderId;
                        formData["kasort"] = kanumber;
                        formData["field"] = key;
                        formData["hideNumber"] = 1;
                    }
                    formDatas.push(formData);
                    kanumber++;
                }
                layui.kaAjax.ajax(layui.kaBgUrl.url("saveGridcolsUser"), function (rs) {
                    if (rs.code == 200) {
                        layui.kaMsg.success("保存成功", "已完成保存表单设计器！");
                    }
                }, formDatas);
            }
        };
        exports('kaGridListHeaderMenu', kaGridListHeaderMenu);
    }
)